import React from 'react';
import { Tabs, Carousel } from 'weaver-mobile';
import { openLink } from '../../../../util';
import * as API_HOMEPAGE from '../../../../apis/homepage';
import Loading from '../../Loading';

class Doc extends React.Component {
  constructor(props) {
    super(props);
    this.onLoadData = this.onLoadData.bind(this);
    this.onLoadMoreData = this.onLoadMoreData.bind(this);
    this.onTouchStart = this.onTouchStart.bind(this);
    this.onTouchMove = this.onTouchMove.bind(this);
    this.onTouchEnd = this.onTouchEnd.bind(this);
    this.onOpenHrm = this.onOpenHrm.bind(this);
    this.onOpen = this.onOpen.bind(this);
    this.onOpenCallback = this.onOpenCallback.bind(this);
    this.state = {
      loading: false,
      loading2: false,
      visible2: false,
      tabs: [],
      tab: {},
      pagenum: 1,
      result: {}
    };
  }

  componentWillMount() {
    const { tabs } = this.props;
    if (tabs && tabs.length) {
      const tab = tabs[0];
      this.setState({ tabs });
      this.onLoadData(tab);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.refreshing) {
      const { tabs } = nextProps;
      if (tabs && tabs.length) {
        const tab = tabs[0];
        this.setState({ tabs });
        this.onLoadData(tab);
      }
    }
  }

  render() {
    const { loading, loading2, visible2, tabs = [], tab = {}, result = {} } = this.state;
    const { showModeId, data = [], topDocIds = [] } = result;
    let tabsCom = null;
    if (tabs && tabs.length > 1) {
      let page = 0;
      for (let i = 0, len = tabs.length; i < len; i++) {
        if (tabs[i].tabid == tab.tabid) {
          page = i;
          break;
        }
      }
      tabsCom = <Tabs tabs={tabs} page={page} renderTabBar={props => <Tabs.ExpandTabBar {...props} fix={8} />} onTabClick={item => this.onLoadData(item)} />;
    }

    let moreCom = null;
    if (visible2 && showModeId != 5) {
      moreCom = (
        <div className="more">
          <Loading loading={loading2}>
            <div className="icon-more" onClick={this.onLoadMoreData} />
          </Loading>
        </div>
      );
    }

    let dataCom = null;
    const imgCom = (
      <Carousel className="top-img" autoplay={true} infinite={true} dotStyle={{ width: 4, height: 4 }} dotActiveStyle={{ width: 5, height: 5 }}>
        {data.map((item, index) => {
          const { docsubject = {} } = item;
          const { name: title, mobilelink } = docsubject;
          return (
            <img
              key={index}
              src={item.docimg}
              alt=""
              style={{ width: '100%', height: '200px', verticalAlign: 'middle' }}
              onLoad={() => {
                window.dispatchEvent(new Event('resize'));
                this.setState({ __height__: 'auto' });
              }}
              onClick={() => this.onOpen(mobilelink)}
            />
          );
        })}
      </Carousel>
    );
    const imgCom2 = (
      <Carousel className="top-img2" autoplay={true} infinite={true} dotStyle={{ width: 4, height: 4 }} dotActiveStyle={{ width: 5, height: 5 }}>
        {data.map((item, index) => {
          const { docsubject = {} } = item;
          const { name: title, mobilelink } = docsubject;
          return (
            <div>
              <img
                key={index}
                src={item.docimg}
                alt=""
                style={{ width: '100%', height: '200px', verticalAlign: 'middle' }}
                onLoad={() => {
                  window.dispatchEvent(new Event('resize'));
                  this.setState({ __height__: 'auto' });
                }}
                onClick={() => this.onOpen(mobilelink)}
              />
              <span className="top-img2-title">{title}</span>
            </div>
          );
        })}
      </Carousel>
    );
    const listCom = (
      <ul className="data-ul">
        {data.map((item, index) => {
          const { docsubject = {}, doccreater = {} } = item;
          const { name: title, img: titleFlag, mobilelink, docid } = docsubject;
          const { userid, name: docCreaterName } = doccreater;
          const isTop = topDocIds.includes(docid);

          return (
            <li
              key={index}
              ref={`li-${index}`}
              onTouchStart={() => this.onTouchStart(index)}
              onTouchMove={() => this.onTouchMove()}
              onTouchEnd={() => this.onTouchEnd(index)}
              onClick={() => this.onOpen(mobilelink, index)}
            >
              <div className="title-div">
                <div className="title">{title}</div>
                {titleFlag && <img ref={isTop ? `title_flag_top_${index}` : `title_flag_${index}`} src={titleFlag} alt="" className={`title-flag ${isTop ? 'title-flag-top' : ''}`} />}
              </div>
              <div className="summary-div">{item.summary}</div>
              <div className="info-div">
                <div className="info-div-items">
                  <div className="info-div-item info-div-user" onClick={(e) => this.onOpenHrm(e, userid)}>{docCreaterName}</div>
                  <div className="info-div-item">{item.docdepartmentname}</div>
                  <div className="info-div-item">{item.doclastmoddate}</div>
                  <div className="info-div-item">{item.doclastmodtime}</div>
                  <div className="info-div-item">{item.doccreatedate}</div>
                  <div className="info-div-item">{item.doccreatetime}</div>
                  <div className="info-div-item">{item.docapprovedate}</div>
                  <div className="info-div-item">{item.docapprovetime}</div>  
                  <div className="info-div-item">{item.docpubdate}</div>
                  <div className="info-div-item">{item.docpubtime}</div>
                </div>
              </div>
            </li>
          );
        })}
      </ul>
    );
    const listCom2 = (
      <ul className="data-ul">
        {data.map((item, index) => {
          const { docsubject = {}, doccreater = {} } = item;
          const { name: title, img: titleFlag, mobilelink, docid } = docsubject;
          const { userid, name: docCreaterName } = doccreater;
          const isTop = topDocIds.includes(docid);

          const titleDivClassName = item.summary ? 'title-div' : 'title-div title-div-no-summary';
          const titleClassName = item.summary ? 'title' : 'title title-no-summary';

          return (
            <li
              key={index}
              ref={`li-${index}`}
              className="left-img-list"
              onTouchStart={() => this.onTouchStart(index)}
              onTouchMove={() => this.onTouchMove()}
              onTouchEnd={() => this.onTouchEnd(index)}
              onClick={() => this.onOpen(mobilelink, index)}
            >
              <div className="left-img">
                <img src={item.docimg} alt="" width="100%" />
              </div>
              <div className="right-list">
                <div className={titleDivClassName}>
                  <div className={titleClassName}>{title}</div>
                  {titleFlag && <img ref={isTop ? `title_flag_top_${index}` : `title_flag_${index}`} src={titleFlag} alt="" className={`title-flag ${isTop ? 'title-flag-top' : ''}`} />}
                </div>
                <div className="summary-div">{item.summary}</div>
                <div className="info-div">
                  <div className="info-div-items">
                  <div className="info-div-item info-div-user" onClick={(e) => this.onOpenHrm(e, userid)}>{docCreaterName}</div>
                  <div className="info-div-item">{item.docdepartmentname}</div>
                  <div className="info-div-item">{item.doclastmoddate}</div>
                  <div className="info-div-item">{item.doclastmodtime}</div>
                  <div className="info-div-item">{item.doccreatedate}</div>
                  <div className="info-div-item">{item.doccreatetime}</div>
                  <div className="info-div-item">{item.docapprovedate}</div>
                  <div className="info-div-item">{item.docapprovetime}</div>  
                  <div className="info-div-item">{item.docpubdate}</div>
                  <div className="info-div-item">{item.docpubtime}</div>
                  </div>
                </div>
              </div>
              <div style={{ clear: 'both' }} />
            </li>
          );
        })}
      </ul>
    );

    switch (showModeId) {
      case '1': // 列表式
        dataCom = listCom;
        break;
      case '2': // 上图式
        dataCom = (
          <React.Fragment>
            {imgCom}
            {listCom}
          </React.Fragment>
        );
        break;
      case '3': // 左图式
        dataCom = listCom2;
        break;
      case '4': // 列表式2
        dataCom = (
          <React.Fragment>
            {imgCom2}
            {listCom2}
          </React.Fragment>
        );
        break;
      case '5': // 上图式2
        dataCom = imgCom;
        break;
      default:
        dataCom = listCom;
    }

    return (
      <div className="content">
        {tabsCom}
        <div className="data">
          <Loading loading={loading}>{dataCom}</Loading>
        </div>
        {moreCom}
      </div>
    );
  }

  onLoadData(tab, pagenum = 1) {
    const { hpid, subCompanyId, eid, ebaseid } = this.props;
    const { tabid } = tab;
    const params = { hpid, subCompanyId, eid, ebaseid, tabid, tabId: tabid, pagenum };

    this.setState({ loading: true, visible2: false, tab, pagenum });
    API_HOMEPAGE.getDocData(params).then(result => {

      console.log("========result=======",result)
      const { data = [], docParams = {}, tabsetting = {} } = result;
      const { topDocIds = [] } = docParams;
      const { showModeId, imgsWithDocSubject = [] } = tabsetting;

      // 将图片和数据合并
      data.forEach((item, index) => {
        const imgs = imgsWithDocSubject[index] ? imgsWithDocSubject[index].imgs : '';
        if (typeof imgs == 'string') {
          item.docimg = imgs;
        } else if (imgs instanceof Array) {
          item.docimg = imgs[0];
        }
      });

      const visible2 = !!(data && data.length);
      this.setState({ loading: false, visible2, result: { showModeId, data, topDocIds } });
    });

    // document.removeEventListener('visibilitychange', this.onOpenCallback);
  }

  onLoadMoreData() {
    const { hpid, subCompanyId, eid, ebaseid } = this.props;
    const { tab, pagenum: oldPagenum, result = {} } = this.state;
    const { tabid } = tab;
    const pagenum = oldPagenum + 1;
    const { data: oldData = [] } = result;
    const params = { hpid, subCompanyId, eid, ebaseid, tabid, tabId: tabid, pagenum };

    this.setState({ loading2: true, pagenum });
    API_HOMEPAGE.getDocData(params).then(result => {
      const { data = [], docParams = {}, tabsetting = {} } = result;
      const { topDocIds = [] } = docParams;
      const { showModeId, imgsWithDocSubject = [] } = tabsetting;

      // 将图片和数据合并
      data.forEach((item, index) => {
        const imgs = imgsWithDocSubject[index] ? imgsWithDocSubject[index].imgs : '';
        if (typeof imgs == 'string') {
          item.docimg = imgs;
        } else if (imgs instanceof Array) {
          item.docimg = imgs[0];
        }
      });

      const visible2 = !!(data && data.length);
      const newData = oldData.concat(data);
      this.setState({ loading2: false, visible2, result: { showModeId, data: newData, topDocIds } });
    });
  }

  onTouchStart(index) {
    const ref = this.refs[`li-${index}`];
    if (ref) {
      ref.style.backgroundColor = '#eee';
    }
  }

  onTouchMove() {
    this.move = true;
  }

  onTouchEnd(index) {
    this.move = false;
    const ref = this.refs[`li-${index}`];
    if (ref) {
      ref.style.backgroundColor = 'transparent';
    }
  }

  onOpenHrm(e, userid) {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();

    window.openLink.openHrm(userid);
  }

  onOpen(url, index) {
    if (!this.move) {
      const ref = this.refs[`title_flag_${index}`];
      ref && (ref.style.display = 'none');

      // document.addEventListener('visibilitychange', this.onOpenCallback);
      openLink(url);
    }
  }

  onOpenCallback() {
    const { tab } = this.state;
    this.onLoadData(tab);
  }
}

export default Doc;
